package com.example.result

import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.protobuf.ProtoBuf
import java.io.InputStream
import java.io.OutputStream

@OptIn(ExperimentalSerializationApi::class)
class BaseSerializer<T>(override val defaultValue: T, val strategy: KSerializer<T>) :
    Serializer<T> {
    override suspend fun readFrom(input: InputStream): T {
        return try {
            val encryptedInput = input.readBytes()
            ProtoBuf.decodeFromByteArray(strategy, encryptedInput)
        } catch (e: SerializationException) {
            throw CorruptionException("Error deserializing proto", e)
        }

    }

    override suspend fun writeTo(data: T, output: OutputStream) {
        val byteArray = ProtoBuf.encodeToByteArray(strategy, data)
        output.write(byteArray)
    }


}
